<template>
  <div class="gtss-review-container">
    <!-- 顶部模块导航 -->
    <div class="module-nav">
      <div class="module-buttons">
        <el-button
          v-for="module in modules"
          :key="module.value"
          :type="activeModule === module.value ? 'primary' : ''"
          @click="changeModule(module.value)"
        >
          {{ module.label }}
        </el-button>
      </div>

      <div class="filter-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索学生姓名/学号"
          clearable
          style="width: 300px; margin-right: 15px"
          @keyup.enter.native="loadReviewList"
        />
        <el-button type="primary" @click="loadReviewList">搜索</el-button>
      </div>
    </div>

    <!-- 审核列表 -->
    <el-card class="review-card">
      <h3>{{ activeModuleLabel }}审核列表</h3>

      <el-table :data="reviewList" v-loading="loading" border stripe>
        <el-table-column prop="studentName" label="学生姓名" width="120" align="center" />
        <el-table-column prop="studentIdStr" label="学号" width="150" align="center" />
        <el-table-column prop="college" label="学院" width="150" align="center" />
        <el-table-column prop="major" label="专业" width="180" align="center" />
        <el-table-column label="文件信息" min-width="300">
          <template slot-scope="{row}">
            <div class="file-info">
              <div class="file-name">
                <i class="el-icon-document"></i>
                {{ formatFilename(row.filename) }}
              </div>
              <div class="file-meta">
                <span>{{ formatFileType(row.fileType) }}</span>
                <span>{{ formatFileSize(row.fileSize) }}</span>
                <span>{{ formatTime(row.uploadTime) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template slot-scope="{row}">
            <el-button
              type="success"
              size="mini"
              @click="handleApprove(row)"
              :disabled="row.status === '审核通过'"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="openRejectDialog(row)"
              :disabled="row.status === '审核驳回'"
            >
              驳回
            </el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-view"
              @click="previewFile(row)"
            >
              预览
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @current-change="handlePageChange"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
      />
    </el-card>

    <!-- 驳回原因对话框 -->
    <el-dialog
      :visible.sync="rejectDialogVisible"
      title="填写驳回原因"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="rejectReason"
        type="textarea"
        :rows="4"
        placeholder="请详细说明驳回原因，以便学生修改..."
      />
      <div slot="footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleReject"
          :disabled="!rejectReason"
        >确认驳回</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      :title="previewTitle"
      width="80%"
      top="5vh"
    >
      <iframe
        v-if="previewDialogVisible"
        :src="previewUrl"
        frameborder="0"
        style="width: 100%; height: 70vh;"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GtssReview',
  data() {
    return {
      modules: [
        { label: '任务书', value: '任务书' },
        { label: '开题报告', value: '开题报告' },
        { label: '中期报告', value: '中期报告' },
        { label: '答辩材料', value: '答辩' },
        { label: '结题报告', value: '结束' }
      ],
      activeModule: '任务书',
      searchKeyword: '',
      reviewList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      rejectDialogVisible: false,
      rejectReason: '',
      currentRejectItem: null,
      previewDialogVisible: false,
      previewUrl: '',
      previewTitle: ''
    };
  },
  computed: {
    activeModuleLabel() {
      return this.modules.find(m => m.value === this.activeModule).label;
    },
    teacherId() {
      return localStorage.getItem('userid');
    }
  },
  mounted() {
    this.loadReviewList();
  },
  methods: {
    // 加载审核列表
    async loadReviewList() {
      this.loading = true;
      try {
        const params = {
          teacherId: this.teacherId,
          category: this.activeModule,
          keyword: this.searchKeyword,
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };

        const res = await this.$axios.get('/gtss/review-list', { params });
        if (res.data.state === 'success') {
          this.reviewList = res.data.data || [];
          this.pagination.total = res.data.total || 0;
        } else {
          this.$message.error('加载数据失败');
        }
      } catch (error) {
        console.error('加载审核列表失败', error);
        this.$message.error('加载数据失败');
      } finally {
        this.loading = false;
      }
    },

    // 切换模块
    changeModule(module) {
      this.activeModule = module;
      this.pagination.currentPage = 1;
      this.loadReviewList();
    },

    // 处理分页变化
    handlePageChange(page) {
      this.pagination.currentPage = page;
      this.loadReviewList();
    },

    // 处理审核通过
    handleApprove(item) {
      this.$confirm(`确认通过 ${item.studentName} 提交的${this.activeModuleLabel}吗？`, '审核确认', {
        confirmButtonText: '确认通过',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        try {
          const request = {
            fileId: item.fileId,
            teacherId: this.teacherId,
            studentId: item.studentId,
            category: this.activeModule,
            result: '通过',
            remark: '审核通过',
            status: this.activeModule
          };

          await this.$axios.post('/gtss/review', request);
          this.$message.success('审核通过成功');
          this.loadReviewList();
        } catch (error) {
          this.$message.error('操作失败');
        }
      }).catch(() => {});
    },

    // 打开驳回对话框
    openRejectDialog(item) {
      this.currentRejectItem = item;
      this.rejectReason = '';
      this.rejectDialogVisible = true;
    },

    // 处理驳回
    async handleReject() {
      try {
        const request = {
          fileId: this.currentRejectItem.fileId,
          teacherId: this.teacherId,
          studentId: this.currentRejectItem.studentId,
          category: this.activeModule,
          result: '驳回',
          remark: this.rejectReason,
          status: this.activeModule
        };

        await this.$axios.post('/gtss/review', request);
        this.$message.warning('已驳回该文件');
        this.rejectDialogVisible = false;
        this.loadReviewList();
      } catch (error) {
        this.$message.error('操作失败');
      }
    },

    // 预览文件
    previewFile(item) {
      // 在实际项目中，这里应该调用后端接口获取文件预览URL
      this.previewTitle = `${item.studentName} - ${this.formatFilename(item.filename)}`;
      this.previewUrl = `/file-preview/${item.fileId}`;
      this.previewDialogVisible = true;
    },

    // 格式化文件名（去除UUID前缀）
    formatFilename(filename) {
      if (!filename) return '';
      const parts = filename.split('_');
      return parts.length > 1 ? parts.slice(1).join('_') : filename;
    },

    // 格式化文件类型
    formatFileType(fileType) {
      const typeMap = {
        'application/pdf': 'PDF',
        'application/msword': 'Word',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word',
        'application/vnd.ms-excel': 'Excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel',
        'text/plain': 'TXT'
      };
      return typeMap[fileType] || fileType.split('/').pop().toUpperCase();
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    },

    // 格式化时间
    formatTime(isoTime) {
      if (!isoTime) return '';
      const date = new Date(isoTime);
      const pad = num => num.toString().padStart(2, '0');
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
    },

    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        '待审核': 'warning',
        '审核通过': 'success',
        '审核驳回': 'danger'
      };
      return statusMap[status] || 'info';
    }
  }
};
</script>

<style scoped>
.gtss-review-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.module-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.module-buttons {
  display: flex;
  gap: 10px;
}

.review-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.file-info {
  padding: 8px 0;
}

.file-name {
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.file-name i {
  margin-right: 8px;
  color: #409EFF;
}

.file-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.filter-bar {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .module-nav {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .filter-bar {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .module-buttons {
    flex-wrap: wrap;
  }
}
</style>
